package com.mxz.common.file.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.mxz.common.core.utils.file.FileUtils;
import com.mxz.common.file.domain.CommFile;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * FastDFS 文件存储
 *
 * @author mxz
 */
@Service
public class FastDfsFileServiceImpl implements CommFileService {
    /**
     * 域名或本机访问地址
     */
    @Value("${fdfs.domain}")
    public String domain;

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口
     *
     * @param file 上传的文件
     * @return CommFile对象
     */
    @Override
    public CommFile uploadFile(MultipartFile file) {
        StorePath storePath = null;
        try {
            String fileExtName = "";
            String originalFilename = file.getOriginalFilename();
            if (originalFilename.lastIndexOf(".") == -1) {
                fileExtName = file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
            } else {
                fileExtName = FilenameUtils.getExtension(originalFilename);
            }
            storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        }
        String url = domain + "/" + storePath.getFullPath();
        String name = FileUtils.getName(url);
        return new CommFile(name, url);
    }

}
